#ifndef _MAILBOX_H_
#define _MAILBOX_H_

#include <stdint.h>
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "esp_err.h"

#ifdef __cplusplus
extern "C" {
#endif

#define MSG_CONTENT_SIZE        4
#define MAX_REGISTERED_TASKS    5
#define MBOX_QUEUE_MAX_SIZE     20

struct app_msg;

typedef void (*msg_callback)(struct app_msg *msg);

typedef enum {
    RESERVE_NORMAL = 0x00,
    RESERVE_SYNC = 0x01,
    RESERVE_ASYNC = 0x02,
    RESERVE_CONTENT = 0x03,
    RESERVE_VALUE = 0x04,
    RESERVE_PTR = 0x05,
    RESERVE_BROADCAST = 0x06,
} msg_reserve_t;

typedef struct app_msg {
    uint8_t sender;         // 发送者ID
    uint8_t type;           // 消息类型
    uint8_t cmd;            // 命令字
    uint8_t reserve;        // 扩展标志位
    union {
        char content[MSG_CONTENT_SIZE];
        int value;
        void *ptr;
    };
    uint32_t data_size;         // 数据大小
    msg_callback callback;      // 异步回调
    struct app_msg* response;    // 同步响应消息
    SemaphoreHandle_t sync_sem;  // 同步信号量
    TaskHandle_t target;         // 发送者Task句柄
} app_msg_t;

// 邮箱注册结构
typedef struct {
    TaskHandle_t task_handle;   // 任务句柄
    QueueHandle_t msg_queue;    // 任务专用消息队列
    uint8_t core_id;            // 所在核心ID
} mailbox_entry_t;

// 跨核通信结构（共享内存）
typedef struct {
    app_msg_t msg;
    void *ext_data;      // 扩展数据指针
    uint16_t data_size;
} __attribute__((packed)) cross_core_msg_t;

mailbox_entry_t* find_mailbox_entry(TaskHandle_t target);
void mailbox_response_or_free(app_msg_t *msg);
void handle_rpc_response(app_msg_t *msg);
esp_err_t mailbox_rpc_call(app_msg_t *msg, TaskHandle_t target, app_msg_t **response, TickType_t timeout);
void mailbox_broadcast(app_msg_t *msg, TickType_t timeout);
esp_err_t mailbox_send_to_task(app_msg_t *msg, TaskHandle_t target, TickType_t timeout);
esp_err_t mailbox_register_current_task();
void mailbox_unregister_task(TaskHandle_t task);

#ifdef __cplusplus
}
#endif

#endif /* _MAILBOX_H_ */